/**
 * @param 所有app下载跳转页拦截微信浏览器提示弹层
 * @author  sheak on 2016/10/28
 * @version v1.0
 * @email 7830957@qq.com
 *
 */

// window.onpopstate = function (e) {
//     if (history.state) {
//         var state = history.state;
//         // console.log(state);
//
//         if (state == "download") {
//             document.getElementById("downloadBox").style.display = "none";
//         }
//     }
// }

// 获取url相关参数
function getUrlParam(name) {
    var reg_url = /^[^\?]+\?([\w\W]+)$/,
        reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
        arr_url = reg_url.exec(window.location.href),
        ret = {};
    if (arr_url && arr_url[1]) {
        var str_para = arr_url[1], result;
        while ((result = reg_para.exec(str_para)) != null) {
            ret[result[1]] = result[2];
        }
    }
    return eval('ret.' + name);
}


//封装getClass
function getClass(tagName, className) {
    if (document.getElementsByClassName) {
        return document.getElementsByClassName(className);
    }
    else {
        var tags = document.getElementsByTagName(tagName);
        var tagArr = [];
        for (var i = 0; i < tags.length; i++) {
            if (tags[i].class == className) {
                tagArr[tagArr.length] = tags[i];
            }
        }
        return tagArr;
    }
}

window.onload = function () {

    // 新增小方/小民扩展
    var _appType = 'xf',
        _appTypeArr = ["xf", "xm"],
        _appScheme = getUrlParam('appId');


    if(_appScheme && _appTypeArr.indexOf(_appScheme) > -1){
        _appType = _appScheme;
    }


    // alert(_appType);

    // 页面添加#download
    // history.replaceState("download", "", location.href.replace("#download", "").replace("#dialog", "") + "#download");

    /*********************************************/

    console.log(_appType);

    if(_appType === 'xf'){
        var newMeta = document.createElement('meta');
        newMeta.charset = 'utf-8';
        newMeta.name = 'apple-itunes-app';
        newMeta.content = 'app-id=1067236066, affiliate-data=myAffiliateData, app-argument=https://itunes.apple.com/cn/app/xiao-fang-fang-zheng-zheng/id1067236066';
    }

    if(_appType === 'xm'){
        var newMeta = document.createElement('meta');
        newMeta.charset = 'utf-8';
        newMeta.name = 'apple-itunes-app';
        newMeta.content = 'app-id=1247720836, affiliate-data=myAffiliateData, app-argument=https://itunes.apple.com/cn/app/%E6%B0%91%E6%97%8F%E8%AF%81%E5%88%B8%E5%B0%8F%E6%96%B9/id1247720836?mt=8';

        // 修改拦截弹层logo
        var _downloadLogo = getClass("img", "adv_img"),
            _downloadSub = getClass("div", "adv_text");

        _downloadLogo[0].src = "";
        _downloadSub[0].innerHTML = '<div>开启你的投资之旅</div><div class="sub">民族证券小方，您的移动财富顾问</div>';
    }

    document.getElementsByTagName('head')[0].appendChild(newMeta);

    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent,
                app = navigator.appVersion;

            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否webapp程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信
                weibo: !!u.match(/Weibo/i), //是否微博
                qq: !!u.match(/QQ\//i) //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    }

    // console.log(browser.versions.qq);


    // 微信端拦截系在页面默认跳转动作
    var show_download_dialog = function (_type) {

        var _dialogStr = '<div style="background: #191919; position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 200; opacity: .88;"></div>';

        if (_type == 'ios') {
            _dialogStr += '<div style="position: fixed; z-index: 300; width: 100%; height: 100%; top: 20px; left: 0; background:url(https://static.fzzqcdn.com/assets/download_from_wechat/imgs/download_app_memb_ios.png) 90% top no-repeat; background-size: 50% auto;"><img src="https://static.fzzqcdn.com/assets/download_from_wechat/imgs/download_app_info_ios.png" style="width: 268px; position: absolute; bottom: 150px; left: 50%; margin-left: -134px;" alt=""></div>';
        } else {
            _dialogStr += '<div style="position: fixed; z-index: 300; width: 100%; height: 100%; top: 20px; left: 0; background:url(https://static.fzzqcdn.com/assets/download_from_wechat/imgs/download_app_memb_android.png) 90% top no-repeat; background-size: 50% auto;"><img src="https://static.fzzqcdn.com/assets/download_from_wechat/imgs/download_app_info_android.png" style="width: 268px; position: absolute; bottom: 150px; left: 50%; margin-left: -134px;" alt=""></div>';
        }

        var dialogDiv = document.createElement("div");
        dialogDiv.innerHTML = _dialogStr;
        dialogDiv.id = 'downloadDialog';

        document.getElementsByTagName('body')[0].appendChild(dialogDiv);

    }

    // 微信端拦截提示手动下载弹层
    var show_by_hand_dialog = function () {

        if(_appType == 'xf'){
            var _dialogStr = '<div style="background: #191919; position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 200; opacity: .88;"></div>';

            _dialogStr += '<div style="position: fixed; z-index: 300; width: 100%; height: 100%; top: 0px; left: 0; "><img src="https://static.fzzqcdn.com/assets/imgs/fz_logo_radius@3x.png" style="width: 100px; margin: 120px auto 10px; display: block;" alt=""><p style="font-size:20px; margin: 0 auto; color: #fff; font-weight:bold; text-align:center;">小方客户端</p><p style="font-size:14px; margin: 10px auto; color: #fff; font-weight:normal; text-align:center;">小方，您的移动财富顾问</p><a style=" background:#D80C18; display: block; width: 260px; height: 50px; line-height: 50px; color: #fff; font-size: 20px; text-align: center; border-radius: 4px; margin: 60px auto 10px; text-decoration: none;" href="javascript:;" id="downLoadByHand">免费下载小方app</a></div>';

            var _downloadBox = document.getElementById("downloadBox");

            if (!_downloadBox) {
                var dialogDiv = document.createElement("div");
                dialogDiv.innerHTML = _dialogStr;
                dialogDiv.id = 'downloadBox';

                document.getElementsByTagName('body')[0].appendChild(dialogDiv);
            } else {
                _downloadBox.style.display = "block";
            }

            // 点击下载执行下载跳转
            document.getElementById("downLoadByHand").addEventListener('click', function () {
                var _downLoadHref = 'https://xf.foundersc.com/download/xf';
                window.location.href = _downLoadHref;
            });
        }

        if(_appType == 'xm'){
            var _dialogStr = '<div style="background: #191919; position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 200; opacity: .88;"></div>';

            _dialogStr += '<div style="position: fixed; z-index: 300; width: 100%; height: 100%; top: 0px; left: 0; "><img src="https://static.fzzqcdn.com/assets/imgs/xm/xm_logo_180.png" style="width: 100px; margin: 120px auto 10px; display: block;" alt=""><p style="font-size:20px; margin: 0 auto; color: #fff; font-weight:bold; text-align:center;">民族证券小方客户端</p><p style="font-size:14px; margin: 10px auto; color: #fff; font-weight:normal; text-align:center;">民族证券小方，您的移动财富顾问</p><a style=" background:#D80C18; display: block; width: 260px; height: 50px; line-height: 50px; color: #fff; font-size: 20px; text-align: center; border-radius: 4px; margin: 60px auto 10px; text-decoration: none;" href="javascript:;" id="downLoadByHand">下载民族证券小方app</a></div>';

            var _downloadBox = document.getElementById("downloadBox");

            if (!_downloadBox) {
                var dialogDiv = document.createElement("div");
                dialogDiv.innerHTML = _dialogStr;
                dialogDiv.id = 'downloadBox';

                document.getElementsByTagName('body')[0].appendChild(dialogDiv);
            } else {
                _downloadBox.style.display = "block";
            }

            // 点击下载执行下载跳转
            document.getElementById("downLoadByHand").addEventListener('click', function () {
                var _downLoadHref = 'http://xfkh.foundersc.com/rewrite/url=http://a.app.qq.com/o/simple.jsp?pkgname=com.foundersc.app.xm';
                window.location.href = _downLoadHref;
            });
        }


    }


    // 优化app安装检测
    var timeout, t = 1000, hasApp = true;

    function testApp(_url) {
        var t1 = Date.now();

        var _tempHref = window.location.href,
            _title = document.title;

        if(_appType == 'xf'){
            var _schemeType = 'fzzqxf://';
        }

        if(_appType == 'xm'){
            var _schemeType = 'fzzqxm://';
        }


        if(!_url || _url.length == 0){
            if(browser.versions.ios){
                var _locHref = _schemeType + 'browser/?url=' + _tempHref;
            }else{
                var  _locHref = _schemeType + 'browser/?title='+_title+'&url=' + _tempHref;
            }
        }else{
            // 扩充短信点击调起
            if(browser.versions.ios){
                var _locHref = _schemeType + '//browser/?url=' + _url;
            }else{
                var _smsTitle = document.getElementById("smsTitle").value,
                    _showShare = document.getElementById("showShare").value,
                    _locHref = _schemeType + 'browser/?title='+encodeURIComponent(_smsTitle)+'&showShare='+_showShare+'&url=' + _url;
            }

        }

        var ifr = document.createElement("iframe");
        ifr.src = _locHref;
        ifr.id = 'openAppBox';
        ifr.style.display = 'none';

        window.location.href = _locHref;

        // alert("location:" + _locHref);

        document.body.appendChild(ifr);
        window.setTimeout(function () {
            document.body.removeChild(ifr);
        }, 3000);

        timeout = setTimeout(function () {
            try_to_open_app(t1);
        }, t);
    }

    function try_to_open_app(t1) {
        var t2 = Date.now();
        if (!t1 || t2 - t1 < t + 200) {
            hasApp = false;
        }
    }

    var getOsv = function(){
        // 判断是否 iPhone 或者 iPod 或者 iPad
        if((navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i))) {

            var _reg = /OS ((\d+_?){2,3})\s/,
                _osv = _reg.exec(navigator.userAgent);

            // 获取系统版本号
            if (_osv.length > 0) {
                return _osv[0].replace('OS', '').replace('os', '').replace(/\s+/g, '').replace(/_/g, '.');
            }
        } else {
            return false;
        }
    }

    // 开始拦截下载链接
    var downloadFromWx = function (_url) {

        // alert(browser.versions.ios);

        if(_appType == "xf"){
            // 小方universal link调起
            var _iosDownloadUrl = 'https://xf.foundersc.com/redirectApp/h5/view/redirect_app/download.html';

            if(!_url || _url.length == 0){

                if(browser.versions.ios){
                    // 新增ios9及以上支持Universal link调起
                    var _osv = getOsv(),
                        _osvArr = _osv.split('.');

                    // alert(_osv);

                    if(_osvArr && _osvArr.length > 0 && parseInt(_osvArr[0]) >= 9){
                        //@TODO: 可能需要调整，否则分享内容无法掉起APP应用
                        var _tempHref = encodeURIComponent((window.location.href).replace("#download", "")).replace("%23","#"),
                            _replacement = _iosDownloadUrl + '?redirectPath=/browser/&url=' + encodeURIComponent(_tempHref),
                            _reg = /http:\/\/([^\/]+)\//i;

                        var _url= _tempHref.replace(_reg, _replacement);

                        // alert(_replacement);

                        window.location.href = _replacement;
                        return false;
                    }
                }
            }
        }

        // if(_appType == "fzzqxm"){
        //     var _iosDownloadUrl = 'https://xf.foundersc.com/redirectApp/h5/view/redirect_app/download_xm.html';
        // }




        if (browser.versions.weixin || browser.versions.weibo || browser.versions.qq) {
            // alert("WX");
            var _platType = '';

            // 根据不同手机系统弹出提示浮层
            if (browser.versions.ios) {
                _platType = 'ios';
            } else if (browser.versions.android) {
                _platType = 'android';
            }

            // console.log(_platType);
            show_download_dialog(_platType);
        } else {
            testApp(_url);
            setTimeout(function () {
                if (hasApp) {
                    // alert(1);
                    //console.log('安装了app');
                } else {
                    // 添加UrlHash
                    // history.pushState("dialog", "", location.href + "#dialog");

                    show_by_hand_dialog();
                }
            }, 2000);
        }

    }


    // 添加时间监听"<a href='javascript:;' class='fz_download_from_wx'>"
    var _downloadLink = getClass("a", "fz_download_from_wx"),
        _autoDownload = getClass("a", "fz_auto_download");

    if (_downloadLink.length > 0) {
        for (var i = 0; i < _downloadLink.length; i++) {
            _downloadLink[i].addEventListener('click', function () {
                // alert(navigator.userAgent);
                downloadFromWx();
            });
        }
    }

    if(_autoDownload.length > 0){
        var _url = _autoDownload[0].getAttribute("locurl");
        // alert(_url);

        _autoDownload[0].onclick = function(){
            downloadFromWx(_url);
        }
        _autoDownload[0].click();

    }


    /*********************************************/
}
